import { View } from '@tarojs/components'
import { Tabs, TabPane } from '@nutui/nutui-react-taro'
import { useMemo, useState } from 'react'
import { useRequest } from 'taro-hooks'
import EmptyState from '../../components/empty-state'
import OrderCard from '../../components/order-card'
import type { Order as OrderCardType } from '../../components/order-card'
import Layout from '../../components/layout'
import { useNavigation } from '../../hooks/useNavigation'
import { getOrderList } from '../../services/product'
import { showSuccess, showModal } from '../../utils/toast'
import './index.less'

const Order = () => {
  const [activeTab, setActiveTab] = useState(0)
  const { navigateTo } = useNavigation()

  // 使用taro-hooks的useRequest获取订单列表
  const { data: orderListData, loading } = useRequest(getOrderList)

  // 将API数据转换为页面所需格式
  const orders: OrderCardType[] = useMemo(() => {
    if (!orderListData?.orders) return []

    return orderListData.orders.map((order) => {
      // 获取第一个产品作为主要显示信息
      const mainProduct = order.products[0]

      return {
        id: order.orderNo,
        date: new Date().toISOString().split('T')[0], // 可以后续从API获取实际日期
        status: 'pending' as const, // 可以根据订单状态映射
        statusText: '待开始',
        statusColor: 'pending',
        amount: `¥${order.totalPrice.toLocaleString()}`,
        project: mainProduct?.name || '装修项目',
        address: order.address.address,
      }
    })
  }, [orderListData])

  const getFilteredOrders = () => {
    if (activeTab === 0) return orders // 全部
    if (activeTab === 1) return orders.filter(order => order.status === 'in_progress') // 进行中
    if (activeTab === 2) return orders.filter(order => order.status === 'completed') // 已完成
    return orders
  }

  const handleTabChange = (index: number) => {
    setActiveTab(index)
  }

  const handleOrderClick = (orderId: string) => {
    navigateTo({
      url: '/pages/order-details/index',
      params: { id: orderId },
    })
  }

  const handleActionClick = (action: string, orderId: string) => {
    switch (action) {
      case 'start':
        showSuccess('开始施工')
        break
      case 'progress':
        navigateTo({
          url: '/pages/order-progress/index',
          params: { id: orderId },
        })
        break
      case 'rebook':
        navigateTo({
          url: '/pages/booking/index',
          params: { orderId },
        })
        break
      case 'contact':
        showModal({
          title: '联系客服',
          content: '客服电话：400-123-4567',
          showCancel: false,
        })
        break
    }
  }

  const renderOrderList = (orderList: OrderCardType[]) => {
    if (orderList.length === 0) {
      return (
        <EmptyState
          icon='📋'
          title='暂无订单'
          description='您还没有任何订单记录'
          buttonText='立即预约'
          onButtonClick={() => navigateTo('/pages/home/index')}
        />
      )
    }

    return (
      <View className='order-list'>
        {orderList.map((order) => (
          <OrderCard
            key={order.id}
            order={order}
            onOrderClick={() => handleOrderClick(order.id)}
            onActionClick={(action) => handleActionClick(action, order.id)}
          />
        ))}
      </View>
    )
  }

  return (
    <Layout title='我的订单' loading={loading} showBack={false}>
      <View className='order-container'>
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          className='order-tabs'
        >
          <TabPane title='全部'>
            {renderOrderList(getFilteredOrders())}
          </TabPane>
          <TabPane title='进行中'>
            {renderOrderList(getFilteredOrders())}
          </TabPane>
          <TabPane title='已完成'>
            {renderOrderList(getFilteredOrders())}
          </TabPane>
        </Tabs>
      </View>
    </Layout>
  )
}

export default Order
